package com.itheima.filter;

import com.itheima.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //0: 将请求对象和响应对象  强转为 符合 http协议的对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1: 获取请求路径URL
        String url = request.getRequestURL().toString();
        //2: 判断url是否包含login 如果包含就放行
        if(url.contains("login")){
            log.info("登录请求,放行");
            chain.doFilter(request,response);
            return;//方法结束 不再往下执行
        }

        //3: 获取请求头中的令牌
        String token = request.getHeader("token");

        //4: 判断令牌是否为存在,如果不存在 返回错误的结果 设置状态码401
        if(token==null||token.length()==0){
            log.info("请求头中无token,返回错误信息");
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setStatus(401);
            return;
        }

        //5: 解析token 如果解析失败就返回 错误信息 状态码401
        try{
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("解析令牌失败,返回错误信息");
            response.setStatus(401);
            return;
        }
        //6: 放行
        log.info("令牌合法,放行");
        chain.doFilter(request,response);
    }
}
